package com.google.codejam.reversewords;

import com.google.codejam.core.test.ACodeJamTestCase;

/**
 * Concrete implementation of the <code>ACodeJamTestCase</code> for the
 * "Reverse Words" problem.
 */
public class ReverseWordsTestCase extends ACodeJamTestCase
{
	protected String[] word_list;
	private static final String  SEPARATOR = " ";
	private              boolean solved    = false;

	/**
	 * Parse the provided, space delimited string of words and instantiates a
	 * <code>String</code> array.
	 *
	 * @param data_str <code>String</code> containing the list of words.
	 */
	public void parseDataString(String data_str)
	{
		word_list = data_str.split(SEPARATOR);
	}

	/**
	 * Solves this test case. In order to solve the test case we create another
	 * <code>String</code> array of the same size and initialize it with the
	 * contents of the original array, but in reverse order.
	 */
	@Override
	public void solve()
	{
		if (solved)
		{
			// if already solved, don't "solve" again, else we re-reverse the list
			return;
		}

		int number_of_words = word_list.length;
		String[] word_list_rev = new String[number_of_words];

		for (int i = 0; i < number_of_words; i++)
		{
			word_list_rev[i] = word_list[(number_of_words - 1) - i];
		}

		word_list = word_list_rev;

		solved = true;
	}

	/**
	 * The result string is obtained by using the internal array (reversed by
	 * calling the <code>solve</code> method) and concatenating the values
	 * (using a <code>StringBuilder</code>). The values are separated by a space
	 * character (' '), as was the case with the original input values.
	 *
	 * @return Space separated, reversed <code>String</code> representation of
	 * the original list of words.
	 */
	@Override
	public String getResultString()
	{
		int number_of_words = word_list.length;
		StringBuilder sb = new StringBuilder(number_of_words * 2);

		for (int i = 0; i < number_of_words - 1; i++)
		{
			// append next entry in the word list
			sb.append(word_list[i]);
			// append separator
			sb.append(SEPARATOR);
		}

		// append last entry in word list (without space)
		sb.append(word_list[number_of_words - 1]);

		return super.getResultString() + sb.toString();
	}
}
